<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2017/11/17
 * Time: 14:18
 */

namespace app\common\model;


use think\Db;
use think\Model;

/**
 * Class LiveStockRecommend 直播晒单
 * @package app\common\model
 *
 * @property integer id
 * @property integer live_channel_id
 * @property string stock_code
 * @property string stock_name
 * @property float stock_raise
 * @property string stock_remark
 * @property string created
 *
 */
class LiveStockRecommend extends Model
{
    protected $table = 'live_stock_recommend';
    protected $pk = 'id';

    private static $SaveFields = [
        'live_channel_id',
        'stock_code',
        'stock_name',
        'stock_raise',
        'stock_remark',
    ];
    public static function getSaveFields() : array {
        return self::$SaveFields;
    }

    /**
     * 保存数据，创建和修改
     *
     * @param array $data
     * @return $this
     */
    public static function upsert(array $data) {
        if (empty($data['id'])) {
            return self::create($data, self::getSaveFields());
        } else {
            return self::update($data, [], self::getSaveFields());
        }
    }

    /**
     * 管理列表
     * @param $liveChannelId
     * @param $rows
     * @param $page
     * @return array
     */
    public static function manageList($liveChannelId, $rows, $page) {
        $q = Db::table('live_stock_recommend r');
        $q->join('live_channel c','c.id=r.live_channel_id','LEFT');
        $q->field('r.*, c.name channel_name');
        $q->order('r.id','desc');

        if ($liveChannelId)
            $q->where('r.live_channel_id','=', $liveChannelId);

        $result = $q->paginate($rows,false, ['page' => $page])
            ->toArray();

        self::format($result['data']);

        return $result;
    }

    /**
     * api列表
     *
     * @param int $liveChannelId
     * @param int $rows
     * @param int $page
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function apiList($rows = 10, $page = 1, $liveChannelId = 0) {

        $q = Db::table('live_stock_recommend r');
        $q->order('r.id','desc');
        if ($liveChannelId) $q->where('r.live_channel_id','=', $liveChannelId);
        $q->page($page,$rows);

        $list = $q->select();

        return $list;
    }

    private static function format(& $list) {
        foreach ($list as & $item) {
            $item['created'] = substr($item['created'],0,16);
        }
    }

}